from typing import List

from entity.database.sqlite import Course
from entity.schema.user_schema import CourseCreate, CourseUpdate, CourseOut


async def create_course(course: CourseCreate) -> CourseOut:
    new_course = await Course.create(**course.dict())
    return await CourseOut.from_tortoise_orm(new_course)

async def get_course_by_id(course_id: int) -> CourseOut | None:
    course = await Course.get_or_none(id=course_id)
    return await CourseOut.from_tortoise_orm(course) if course else None

async def update_course(course_id: int, course_update: CourseUpdate) -> CourseOut | None:
    course = await Course.get_or_none(id=course_id)
    if not course:
        return None
    await course.update_from_dict(course_update.dict(exclude_unset=True)).save()
    return await CourseOut.from_tortoise_orm(course)

async def delete_course_by_id(course_id: int) -> bool:
    course = await Course.get_or_none(id=course_id)
    if not course:
        return False
    await course.delete()
    return True

async def count_users_in_course(course_id: int) -> int:
    course = await Course.get_or_none(id=course_id)
    if not course:
        return 0
    return await course.users.all().count()